/*
Description: $.messager
Author: Kris Zhang
require: 
  string.format.js
  $.fn.dialog
*/

$.messager = (function() {

	  /*
	  * popup message
	  */
	  var msghtml
	  = ''
		  + '<div class="dialog modal fade msg-popup">'
		  + '<div class="modal-dialog modal-sm">'
		  +   '<div class="modal-content">'
		  +     '<div id="_message_" class="modal-body text-center"></div>'
		  +   '</div>'
		  + '</div>'
		  + '</div>'
		  ;
	  
	var configTemplate = {
		msg : "[无输出信息]",
		placement : "bottom", // top , bottom
		delay : 1500,
		style : "",
		template : null,
		oncreate : function(){return true},
		ondestroy : function(){return true}
	}

  var alert = function(title, message) {
    var model = $.messager.model;

    if (arguments.length < 2) {
      message = title || "";
      title   = "&nbsp;"
    }

    $("<div>" + message + "</div>").dialog({
        title:   title
        // override destroy methods;
      , onClose: function() {
          $(this).dialog("destroy");
        }
      , buttons: [{
            text: model.ok.text
          , classed: model.ok.classed || "btn-success"
          , click: function() {
              $(this).dialog("destroy");
            }
        }]
    });
  };

  var confirm = function(title, message, callback) {
    var model = $.messager.model;

    $("<div>" + message + "</div>").dialog({
        title:   title
        // override destroy methods;
      , onClose: function() {
          $(this).dialog("destroy");
        }
      , buttons: [{
            text: model.ok.text
          , classed: model.ok.classed || "btn-success"
          , click: function() {
              $(this).dialog("destroy");
              callback && callback();
            }
        },
        {
            text: model.cancel.text
          , classed : model.cancel.classed || "btn-danger"
          , click: function() {
              $(this).dialog("destroy");
            }
        }]
    });
  };


  var $msgbox;

  var popup = function(config) {
	  var cfg;
	  if(typeof config == "string"){
		  cfg = configTemplate;
		  cfg.msg = config;
	  }else{
		  cfg = $.extend(configTemplate, config); 
	  }
	  var message = cfg.msg;
    if (!$msgbox) {
      $msgbox = $(cfg.template || msghtml);
      if(cfg.style){
    	  $msgbox.find("#_message_").attr("style", cfg.style);
      }
      if(cfg.placement == "bottom"){
    	  $msgbox.css("bottom", 10);
      }
      if(cfg.oncreate()){
          $('body').append($msgbox);
      }
    }

    $msgbox.find("#_message_").html(message);
    $msgbox.modal({show: true, backdrop: false});

    setTimeout(function() {
      $msgbox.modal('hide');
    }, cfg.delay);
  };

  return {
      alert:   alert
    , popup:   popup
    , confirm: confirm
  };

})();


$.messager.model = {
    ok: { text : "OK", classed : 'btn-success' },
    cancel: { text : "Cancel", classed : 'btn-danger' }
};
